package com.dalin.platform.log.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ResourceBundle;

import com.dalin.common.utils.FileUtils;
import com.dalin.framework.action.StrutsTwoAction;

/*****************************************************************************
 * @content: 类信息                                                                                                                                  *
 * @author : 那建林                                                                                                                                 *
 * @crtDate: 2010-06-23                                                     *
 * @modDate: 2010-06-23                                                     *
 * @version: 1.00                                                           *
 ****************************************************************************/
public class SystemBackupAction extends StrutsTwoAction {

	public String execute() throws Exception {
        super.printInfo("", "===== this action begin");
        String absolutePath = super.getAbsolutePhysicalPath();
        absolutePath += "fileInfo/database/databaseBackup.lin";
        boolean isSuccessful = this.backupData(absolutePath);
        if (isSuccessful) {
        	setResContent(getReq().getContextPath()
        			+ "/fileInfo/database/databaseBackup.zip");
        } else {
        	setResContent("error");
        }
        super.printInfo("", "===== this action end");
        return null;
    }
	
	private boolean backupData(String absolutePhysicalFilePath) {
		StringBuffer buf = new StringBuffer("exp ");
		ResourceBundle rb = ResourceBundle.getBundle("jdbc");
		String jdbcUrl = rb.getString("jdbc.url");
		int lastColon = jdbcUrl.lastIndexOf(":") + 1;
		String dbName = jdbcUrl.substring(lastColon, jdbcUrl.length());
		buf.append(rb.getString("jdbc.username")).append("/")
			.append(rb.getString("jdbc.password")).append("@")
			.append(dbName).append(" file=")
			.append(absolutePhysicalFilePath);
		log.info("执行命令" + buf.toString());
		try {
			Process process = Runtime.getRuntime().exec(buf.toString());
			BufferedReader b = new BufferedReader(
					new InputStreamReader(process.getErrorStream()));
			String line = null;
			while((line = b.readLine()) != null) {
				log.info(line);
			}   
			int value  = process.exitValue();   
			if (value != 0) {   
				log.error("执行命令" + buf.toString()
						+ "失败!  exit value =" + value);
				return false;
			}
			FileUtils.zipFiles(
					new File(absolutePhysicalFilePath), 
					new File(absolutePhysicalFilePath.substring(
							0,absolutePhysicalFilePath.length() - 4) + ".zip"));
			FileUtils.deleteFiles(new File(absolutePhysicalFilePath));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}